package com.cclinux.projects.actcampus.controller.cust;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.cclinux.framework.annotation.LoginIgnore;
import com.cclinux.framework.core.platform.controller.BaseController;
import com.cclinux.framework.core.domain.ApiResult;
import com.cclinux.framework.exception.AppException;
import com.cclinux.projects.actcampus.service.cust.PublicService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Notes: 常用模块
 * @Author: cclinux0730 (weixin)
 * @Date: 2024/2/18 7:32
 * @Ver: ccminicloud-framework 3.2.1
 */

@RestController("ActCampusPublicController")
public class PublicController extends BaseController {

    @Resource(name = "ActCampusPublicService")
    PublicService publicService;

    @RequestMapping("/comm/upload")
    @ResponseBody
    public ApiResult upload(
            @RequestParam(value = "file") MultipartFile file ) throws Exception {

        if (file.isEmpty()) throw new AppException("上传文件不能为空");

        String fileName = file.getOriginalFilename();
        String extend = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        extend = extend.toLowerCase();
        if (!StrUtil.equalsAny(extend, ".png", ".jpg", ".jpeg"))
            throw new AppException("只能上传png,jpg格式的图片");

        String url = publicService.upload(file);

        return ApiResult.success(MapUtil.of("fileID", url));
    }

    @LoginIgnore
    @RequestMapping("/api/decryptPhoneNumber")
    @ResponseBody
    public ApiResult decryptPhoneNumber(@RequestBody Map<String, String> requestBody){


        Map<String, Object> resultMap = null;
        try {
            String encryptedData = requestBody.get("encryptedData");
            String sessionKey = requestBody.get("sessionKey");
            String iv = requestBody.get("iv");

            // 添加 BouncyCastleProvider 提供更多的加密算法支持
            Security.addProvider(new BouncyCastleProvider());

            // 对数据进行解码
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            // 创建 Cipher 实例
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivBytes));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, params);

            // 解密数据
            byte[] resultBytes = cipher.doFinal(encryptedBytes);
            String result = new String(resultBytes, StandardCharsets.UTF_8);

            // 使用 Jackson 解析 JSON 结果
            ObjectMapper mapper = new ObjectMapper();
            resultMap = mapper.readValue(result, Map.class);
            System.out.println("解密后的手机号: " + resultMap.get("phoneNumber"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ApiResult.success(resultMap.get("phoneNumber"));
    }

    private static final String appId = "wx6ca5394fe35e5c46";
    private static final String appSecret = "7a304f5dbb0878e136cc1ff52f26ae26";
    private static final OkHttpClient client = new OkHttpClient();
    private static final ObjectMapper mapper = new ObjectMapper();

    @LoginIgnore
    @PostMapping("/api/login")
    public Map<String, String> login(@RequestBody Map<String, String> requestBody) throws Exception {
        String code = requestBody.get("code");
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, appSecret, code);
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                JsonNode jsonNode = mapper.readTree(response.body().string());
                String sessionKey = jsonNode.get("session_key").asText();
                String openId = jsonNode.get("openid").asText();
                Map<String, String> result = new HashMap<>();
                result.put("sessionKey", sessionKey);
                result.put("openId", openId);
                return result;
            } else {
                throw new Exception("获取 sessionKey 失败");
            }
        }
    }
}
